<template>
    <el-container>
        <el-header style="text-align: center;">
            <el-row>
                <el-col :span="23">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{ path: '/' }">登录页</el-breadcrumb-item>
                        <el-breadcrumb-item><a href="/main/TestExamFenYe">业务管理</a></el-breadcrumb-item>
                        <el-breadcrumb-item>分页查询</el-breadcrumb-item>
                    </el-breadcrumb>
                </el-col>
            </el-row>
            <h1>登录日志增删改查</h1>
        </el-header>
        <!-- el-main 是elementUI的布局容器，用于放置页面的主要内容，
         类似的还有el-container、el-aside、el-footer、el-header -->
        <el-main style=" justify-content: center; align-items: center;">
            <el-row style="">
                <!-- 搜索表单，要与pojoTestQuery绑定 -->
                <el-form :model="pojoTestQuery" :inline="true" align="center" style="">
                    <el-form-item label="产品名">
                        <el-input placeholder="请输入产品名" v-model="pojoTestQuery.productName" autocomplete="off"
                            style="width:70%;" :clearable="true" />
                    </el-form-item>
                    <el-form-item label="账单编码">
                        <el-input placeholder="输入账单编码" v-model="pojoTestQuery.billCode" autocomplete="off"
                            style="width: 70%;" :clearable="true" />
                    </el-form-item>
                    <el-form-item label="总价">
                        <el-input placeholder="请输入总价" v-model="pojoTestQuery.totalPrice" style="width:70%;"
                            :clearable="true" />
                    </el-form-item>
                    <el-form-item label="供应商名称">
                        <el-input placeholder="请输入供应商名称" v-model="pojoTestQuery.provider.proName" style="width:70%;"
                            :clearable="true" />
                    </el-form-item>
                    <el-form-item label="创建时间">
                        <el-date-picker v-model="pojoTestQuery.creationDate" type="datetime" placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            style="width: 70%;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="供应商名称">
                         <!--- 因为要获取表单值传回给pojoTestQuery，所以这里的el-select的v-model绑定pojoTestQuery.provider.id --->
                        <el-select :clearable="true" v-model="pojoTestQuery.provider.id" placeholder="请选择供应商名称"> 
                            <el-option v-for="(item, index) in providerList" :key="index" :label="item.proName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>


                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch()">搜索</el-button>
                        <el-button type="info" icon="el-icon-refresh" @click="clearSelection()">重置</el-button>
                        <el-button type="success" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
                        <el-button type="success" icon="el-icon-printer"
                            @click="handleExportExcel()">前端导出excel</el-button>

                        <el-button type="success" icon="el-icon-printer"
                            @click="handleExportExcelFromBackUp()">后端导出excel</el-button>
                        <el-button type="success" icon="el-icon-upload"
                            @click="handleImportExcelFromBackUp()">后端入excel</el-button>
                        <el-tooltip class="item" effect="light" content="请选择要删除的记录！" placement="top"
                            :disabled="this.ids.length === 0 ? false : true">
                            <el-button type="danger" :disabled="this.ids.length === 0 ? true : false"
                                icon="el-icon-delete" @click="handleDelete()">批量删除</el-button>
                        </el-tooltip>
                    </el-form-item>
                </el-form>
            </el-row>
            <!-- type="selection" ref="multipleTable"是自定义的唯一标识 
        选择框 type="index" 序号 prop:每一行的属性 align="center" 居中 -->
            <el-table :data="pojoList" :model="pojoTestTable" @selection-change="handleSelectionChange" border stripe
                height="360px" style="width: 100%; margin: 0 auto;">
                <!-- 查询列表的表格，要与pojoTestTable绑定 -->
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column type="index" label="序号" width="50px" align="center">
                </el-table-column>
                <el-table-column prop="creationDate" label="创建时间" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="createdBy" label="创建者" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="modifyDate" label="修改时间" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="modifyBy" label="修改者" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="productName" label="产品名称" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="productDesc" label="产品描述" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="productUnit" label="产品描述" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="billCode" label="账单编码" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="totalPrice" label="总价" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="productCount" label="产品数量" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="isPayment" label="是否支付" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="providerId" label="供应商ID" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="provider.proName" label="供应商名称" width="auto" align="center">
                </el-table-column>

                <el-table-column align="center" label="删除" width="80px" fixed="right">
                    <template slot-scope="scope"> <!-- 作用域插槽，可以获取当前行的数据 -->
                        <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="修改" width="80px" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="getById(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页，handleSizeChange是分页大小变化的事件，handleCurrentChange是当前页变化的事件 -->
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pojoTestQuery.currentIndex" :page-sizes="[5, 10, 15, 20, 50, 100]" :page-size="5"
                layout="total, sizes, prev, pager, next, jumper" :total="total" style="float: right;">
            </el-pagination>

            <!-- 新增/修改表单，打开表单:visible.sync="open" 点击表单外不关闭 :close-on-click-modal="false" -->
            <el-dialog :title="this.updateType" :visible.sync="open" :close-on-click-modal="false"
                @close="addDialogClose" width="25%">
                <el-form :model="pojoTestTable" label-width="80px" :rules="rules" ref="multipleTable">
                    <el-form-item label="产品名称" prop="productName">
                        <el-input placeholder="请输入产品名称" v-model="pojoTestTable.productName"
                            autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="账单编码" prop="billCode">
                        <el-input placeholder="请输入账单编码" v-model="pojoTestTable.billCode" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="产品描述" prop="productDesc">
                        <el-input placeholder="请输入产品描述" v-model="pojoTestTable.productDesc"
                            autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="产品单位" prop="productUnit">
                        <el-input placeholder="请输入产品单位" v-model="pojoTestTable.productUnit"
                            autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="总价" prop="totalPrice">
                        <el-input placeholder="请输入总价" v-model="pojoTestTable.totalPrice" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="产品总数" prop="productCount">
                        <el-input placeholder="请输入产品总数" v-model="pojoTestTable.productCount" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="是否支付" prop="isPayment">
                        <el-input placeholder="请输入是否支付" v-model="pojoTestTable.isPayment" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="供应商Id" prop="providerId">
                        <el-input placeholder="请输入供应商Id" v-model="pojoTestTable.providerId" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="创建者" prop="createdBy">
                        <el-input placeholder="请输入创建者" v-model="pojoTestTable.createdBy" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="创建时间" prop="creationDate">
                        <el-date-picker v-model="pojoTestTable.creationDate" type="datetime" placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="修改者" prop="modifyBy">
                        <el-input placeholder="请输入创建者" v-model="pojoTestTable.modifyBy" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="修改时间" prop="modifyDate">
                        <el-date-picker v-model="pojoTestTable.modifyDate" type="datetime" placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click="open = false">取 消</el-button>
                    <el-button type="primary" @click=vaildForm()>确 定</el-button>
                </div>
            </el-dialog>
        </el-main>
        <el-footer>

        </el-footer>
    </el-container>

</template>

<script>


import * as XLSX from 'xlsx'

export default {
    name: 'BillsManager',
    // props: {
    //     constVal:String  父传子组件的时候，在子组件这样接收，用this.constVal直接调用
    // },
    data() {
        return {
            open: false,           // 是否显示新增/修改表单
            updateType: "",        // 在表单左上角显示的是新增还是修改
            total: null,           // 总记录数
            pojoList: [],          // 列表数据，在执行getList()方法时赋值
            providerList: [],     // 供应商列表
            selectedRows: [], // 批量选择的行数据
            names: [],             // 批量选择的行名称
            ids: [],               // 批量选择的行id           
            creationDate: '',
            circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
            // tabel对象
            pojoTestTable: {
                id: null,
                productDesc: null,
                productUnit: null,
                isPayment: null,
                createdBy: null,
                creationDate: null,
                modifyBy: null,
                modifyDate: null,
                productName: null,
                providerId: null,
                billCode: null,
                totalPrice: null,
                productCount: null,
                provider: {
                    id: null,
                    proName: null,
                },     // 供应商列表
            },
            // 表单对象
            pojoTestQuery: {
                id: null,
                productDesc: null,
                productUnit: null,
                isPayment: null,
                createdBy: null,
                creationDate: null,
                modifyBy: null,
                modifyDate: null,
                productName: null,
                providerId: null,
                billCode: null,
                totalPrice: null,
                productCount: null,
                provider: {
                    id: null,
                    proName: null,
                },    // 供应商列表
                currentIndex: 1,
                pageSize: 5,
            },

            rules: {
                productName: [
                    { required: true, message: '请输入日志名称', trigger: 'blur' },
                ],
                billCode: [
                    { required: true, message: '请输入登录方法', trigger: 'blur' },
                ],
                creationDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                totalPrice: [
                    { required: true, message: '请输入登录等级', trigger: 'blur' }
                ],
            }

        };
    },
    mounted: function () {    // 页面加载完成后执行
        this.getList();
        // console.log("----分页里面，query传值-----",this.$route.query) 接收路由传值，现在不需要
    },
    watch: {
        provider(newVal, oldVal) {
            console.log("供应商列表发生变化，newVal = ", newVal, "oldVal = ", oldVal);
            this.pojoTestQuery.providerId = newVal.id;
            this.getList();
        },
        deep: true
    },
    methods: {
        // handle 处理提示消息
        handleUpdate(pojoTestTable) {
            const copyPojo = JSON.parse(JSON.stringify(pojoTestTable));
            this.$confirm('修改名称为：' + copyPojo.productName + '的记录?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.update(copyPojo);
                this.open = false;
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消修改' });
            });
        },


        handleInsert() {
            var insertObj = JSON.parse(JSON.stringify(this.pojoTestTable));
            this.$confirm('新增名称为：' + this.pojoTestTable.productName + '的记录?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.insert(insertObj);
                this.open = false;
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消新增' });
            });
        },

        handleDelete(row) {
            // const ids = row.id || this.ids
            // const names = row.productName || this.names
            var ids = null;
            var names = null;
            if (row != null) {
                console.log("row不为空！row = ", row);
                ids = row.id
                names = row.productName
            } else {
                console.log("ids = ", this.ids);
                ids = this.ids
                names = this.names
            }

            // 删除登录日志(集成批量删除)
            this.$confirm('此操作将永久删除记录名为：' + names + '，是否继续?', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delete(ids);
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消删除' });
            });
        },

        handleAdd() {
            this.pojoTestTable = {}
            this.updateType = "新增";
            this.open = true;
        },

        handleSearch() {
            this.getList();
        },

        /**
         * 后端导出excel
         */
        handleExportExcelFromBackUp() {
            this.$confirm('此操作将导出当前页所有数据，是否继续?', '导出提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get("http://localhost:8082/bills/exportEquipmentExcel", {
                    responseType: 'blob',   // 重要：告诉axios预期服务器返回的数据类型
                })
                    .then(res => {
                        const blob = new Blob([res.data], {
                            type: "application/vnd.ms-excel",
                        });
                        // 获取 文件名
                        var fileName = decodeURIComponent("学生信息.xls");
                        //创建一个 a 标签
                        const link = document.createElement("a");
                        //不显示a标签
                        link.style.display = "none";
                        // 给a 标签的href属性赋值
                        link.href = URL.createObjectURL(blob);
                        link.setAttribute("download", fileName);
                        //把a标签插入页面中
                        document.body.appendChild(link);
                        link.click();
                        //点击之后移除a标签
                        document.body.removeChild(link);
                    }).catch(error => {
                        //请求失败，触发catch中的函数 可省略
                        console.log(error)
                        console.log("请求失败...");
                    })

            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导出' });
            });
        },

        /**
         * 前端导出excel
         */
        handleExportExcel() {
            this.$confirm('此操作将导出当前页所有数据，是否继续?', '导出提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                try {
                    // 创建工作簿
                    const wb = XLSX.utils.book_new();

                    // 准备导出数据 - 注意这里应该使用 this.pojoList 而不是 this.pojoTestTable
                    const exportData = this.pojoList.map(item => ({
                        'ID': item.id,
                        '登录名': item.productName,
                        '登录时间': item.creationDate,
                        '登录方法': item.billCode,
                        '登录等级': item.totalPrice,
                    }));

                    // 将数据转换为工作表
                    const ws = XLSX.utils.json_to_sheet(exportData);

                    // 将工作表添加到工作簿
                    XLSX.utils.book_append_sheet(wb, ws, '登录日志数据');

                    // 生成Excel文件并下载
                    const fileName = `登录日志_${new Date().toLocaleString().replace(/[/:\\]/g, '-')}.xlsx`;
                    XLSX.writeFile(wb, fileName);

                    // 显示成功通知
                    this.$message({
                        message: '导出成功',
                        type: 'success'
                    });
                } catch (error) {
                    console.error('导出失败:', error);
                    this.$message.error('导出失败，请查看控制台详情');
                }
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导出' });
            });
        },

        /**
         * 后端导入excel
         */
        handleImportExcelFromBackUp() {
            this.$confirm('此操作将导入excel数据，是否继续?', '导入提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post("http://localhost:8082/bills/importEquipmentExcel")
                    .then(response => {
                        console.log(response);
                        this.$message({
                            message: '导入成功',
                            type: 'success'
                        });
                        this.getList();
                    }).catch(error => {
                        console.log(error);
                        this.$message.error('导入失败，请查看控制台详情');
                    })
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导入' });
            });
        },

        // 具体的业务处理
        getproviderList() {
            // 获取供应商列表
            this.$axios.get('http://127.0.0.1:8082/provider/list')
                .then(response => {
                    console.log("供应商列表：", response.data.data);
                    this.providerList = response.data.data;
                }).catch(error => {
                    console.log("query failed" + error);
                });
        },
        getList() {
            // 获取登录日志
            console.log("查询的对象：", this.pojoTestQuery);
            this.$axios.post('http://127.0.0.1:8082/bills/fenYeList', this.pojoTestQuery)
                .then(response => {
                    console.log("后台返回的对象", response.data.data);
                    this.pojoList = response.data.data.pojoTestList
                    this.total = response.data.data.totalCount
                    this.getproviderList()

                }).catch(error => {
                    console.log("query failed" + error);
                });
        },


        delete(loginLogIds) {
            console.log("删除的对象：", loginLogIds);
            this.$axios.delete('http://127.0.0.1:8082/bills/deleteBatch/' + loginLogIds)
                .then(response => {
                    if (response.data.data > 0) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        });
                    }
                    this.getList();
                }).catch(error => {
                    console.log("delete failed" + error);
                });
        },

        getById(id) {
            this.open = true;
            this.updateType = "修改";
            // 获取登录日志
            this.$axios.get('http://127.0.0.1:8082/bills/getById/' + id)
                .then(response => {
                    this.pojoTestTable = {};
                    this.pojoTestTable = response.data.data;
                    this.open = true;
                }).catch(error => {
                    console.log("query failed" + error);
                });
        },

        update(pojoTestTable) {
            console.log("更新的对象：", pojoTestTable);
            // 修改登录日志 因为要传对象，用逗号，所以最后update路径不写 /
            this.$axios.put('http://127.0.0.1:8082/bills/update', pojoTestTable)
                .then(response => {
                    console.log(response);
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.getList();
                }).catch(error => {
                    console.log("update failed" + error);
                });
        },

        insert(insertObj) {
            // 新增登录日志 最后insert路径不写 /
            this.$axios.post('http://127.0.0.1:8082/bills/add', insertObj)
                .then(response => {
                    console.log(response);
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    this.open = false;
                    this.getList();
                }).catch(error => {
                    console.log("insert failed" + error);
                });
        },


        // 表格相关

        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pojoTestQuery.pageSize = val;
            this.getList();

        },

        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pojoTestQuery.currentIndex = val;
            this.getList();
        },

        /**
         * 验证表单
         * @param pojoTestTable 登录日志对象 
         */
        vaildForm() {
            // 表单验证
            this.$refs.multipleTable.validate((valid) => {
                if (valid) {
                    this.submitForm(this.pojoTestTable);
                } else {
                    alert('请检查输入项');
                    return false;
                }
            });
        },

        /**
         * 提交表单
         * @param pojoTestTable 登录日志对象
         */
        submitForm() {
            // 新增或修改登录日志   
            if (this.pojoTestTable.id) {
                // 有主键修改登录日志
                this.updateType = "修改";
                this.handleUpdate(this.pojoTestTable);
            } else {
                // 没有主键就新增
                this.updateType = "新增";
                this.handleInsert(this.pojoTestTable);
                this.getList();
            }
        },



        /**
         * 清空选择
         * @param {Object} rows 行数据
         */
        clearSelection() {
            this.pojoTestQuery = {
                id: null,
                productDesc: null,
                productUnit: null,
                isPayment: null,
                createdBy: null,
                creationDate: null,
                modifyBy: null,
                modifyDate: null,
                productName: null,
                providerId: null,
                billCode: null,
                totalPrice: null,
                productCount: null,
                provider: {
                    id: null,
                    proName: null,
                },
                pageSize: this.pojoTestQuery.pageSize,
                currentIndex: this.pojoTestQuery.currentIndex,
            };
            this.getList();
        },

        addDialogClose() {
            this.$refs['multipleTable'].resetFields();
        },

        /**
         * 选择行对象
         * @param rows 行数据
         */
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);

                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.names = selection.map(item => item.productName);
            console.log(this.ids);
            console.log(this.names);
        },



    },
};
</script>
<style scoped></style>